#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
YML=$DIR/../containers/app.yml
if [ -f $YML ]
then
  echo "cannot run test if $YML exists."
  exit
fi

check_value () {
  VAR=$1
  VAL=$2
  YML=$3
  if ! [[ $(grep $VAR $YML |sed -e "s/  $VAR: //") == "$VAL" ]]
  then
    echo $VAR is NOT $VAL
    echo TEST FAILED. Aborting. 
    exit 1
  fi
}

hostname='test.myhost.com'
developer='admin@mail.myhost.com'
smtp_address='smtp.myhostn.com'
smtp_port=''
smtp_user='smtpuser'
smtp_pass='smtp-pw'
notification=''
letsencrypt='le@myhost.com'
maxmind=''
$DIR/../discourse-setup --skip-connection-test --skip-rebuild <<EOF 
$hostname
$developer
$smtp_address
$smtp_port
$smtp_user
$smtp_pass
$notification
$letsencrypt
$maxmind


EOF
check_value DISCOURSE_HOSTNAME $hostname $YML
check_value DISCOURSE_SMTP_ADDRESS $smtp_address $YML
check_value DISCOURSE_SMTP_PORT 587 $YML
check_value DISCOURSE_SMTP_USER_NAME $smtp_user $YML
check_value DISCOURSE_SMTP_PASSWORD \"$smtp_pass\" $YML
check_value DISCOURSE_SMTP_DOMAIN $hostname $YML
check_value DISCOURSE_NOTIFICATION_EMAIL noreply@$hostname $YML
echo "################################ Initial install succeeded. ###################################"
echo "Now running edit test."
hostname='new.myhost.com'
developer='new@mail.myhost.com'
smtp_address='new.myhostn.com'
smtp_port='2525'
smtp_user='newuser'
smtp_pass='new-smtp-pw'
notification='somuser@otherhost.com'
smtp_domain=otherhost.com # NOTE: script uses notification hostnme
letsencrypt='le-new@myhost.com'
maxmind='maxthisone'
$DIR/../discourse-setup --skip-connection-test --skip-rebuild <<EOF 
$hostname
$developer
$smtp_address
$smtp_port
$smtp_user
$smtp_pass
$notification
$letsencrypt
$maxmind


EOF
check_value DISCOURSE_HOSTNAME $hostname $YML
check_value DISCOURSE_SMTP_ADDRESS $smtp_address $YML
check_value DISCOURSE_SMTP_PORT $smtp_port $YML
check_value DISCOURSE_SMTP_USER_NAME $smtp_user $YML
check_value DISCOURSE_SMTP_PASSWORD \"$smtp_pass\" $YML
check_value DISCOURSE_SMTP_DOMAIN $smtp_domain $YML
check_value DISCOURSE_NOTIFICATION_EMAIL $notification $YML
echo "################################ Update of values succeeded. ###################################"
echo "Removing $YML*"
rm $YML*

echo "Test succeeded. Removing $YML"
rm $YML
